<template>
  <el-drawer v-model="visible" :title="title" :size="900" destroy-on-close :close-on-click-modal="false"
    :close-on-press-escape="false" @close="handleClose" :before-close="handleBeforeClose">
    <!-- 内容区域 -->
    <div class="drawer-content">
      <el-tabs v-model="activeTab" class="course-tabs">
        <el-tab-pane :label="$t('course.basicInfo')" :name="BASIC_INFO">
          <template #label>
            <span class="flex items-center gap-1 edit-btn-wrapper">
              {{ $t('course.basicInfo') }}
              <span v-if="isBasicDraft" class="draft-dot"></span>
            </span>
          </template>
          <BasicInfo ref="basicInfoRef" :data="props.data" @update:data="handleBasicInfoUpdate" />
        </el-tab-pane>
        <el-tab-pane :label="$t('course.courseDirectory')" :name="COURSE_DIRECTORY"
          :disabled="isCourseDirectoryDisabled">
          <template #label>
            <span class="flex items-center gap-1 edit-btn-wrapper"
              :class="{ 'disabled-tab': isCourseDirectoryDisabled }">
              {{ $t('course.courseDirectory') }}
              <span v-if="isDirectoryDraft" class="draft-dot"></span>
            </span>
          </template>
          <CourseDirectory ref="courseDirectoryRef" :data="props.data" />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 底部按钮区域 -->
    <template #footer>
      <div class="flex justify-end gap-3">
        <el-button @click="handleCancel">{{ $t('common.cancelTxt') }}</el-button>
        <el-button v-if="isEditDraft" @click="handleSaveDraft" :loading="isSaveDraftLoading">
          {{ $t('course.saveDraft') }}
        </el-button>
        <el-button type="primary" :loading="isLoading" @click="() => handleConfirm(false)">
          {{ $t('common.submitTxt', ['']) }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { cloneDeep, isEqual } from '@vben/utils';
import { computed, ref, watch, markRaw } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { $t } from '#/locales/index.js'
import BasicInfo from './basic-info.vue'
import CourseDirectory from './course-directory.vue'
import { HAD_DRAFT_MAP, type CourseItem } from './types'
import {
  createCourseInfoApi, updateCourseInfoApi, saveDraftCourseInfoApi,
  createCourseDirectoryApi, saveDraftCourseDirectoryApi, getCourseDirectoryApi,
  getCourseDetailApi
} from '#/api/manage/course'
import { NODE_TYPE, initBasicInfoFormData } from './types'
import { safeMergeObject } from '#/utils/objectMerge'
import { SvgFailIcon, SvgTipIcon, SvgSuccessIcon } from '@vben/icons'
import { useMessageBox } from '#/hooks/useMessageBox'

const BASIC_INFO = 'basicInfo'
const COURSE_DIRECTORY = 'courseDirectory'
interface Props {
  modelValue: boolean
  mode: 'add' | 'edit'
  data?: CourseItem
}
interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', data?: CourseItem): void
  (e: 'saveDraft', data?: CourseItem): void
  (e: 'cancel'): void
  (e: 'update:data', data: CourseItem): void
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  mode: 'add',
  data: undefined
})
const { confirm } = useMessageBox({})
const emit = defineEmits<Emits>()
const isLoading = ref(false)
const isSaveDraftLoading = ref(false)
// Tab 相关
const activeTab = ref(BASIC_INFO)
const basicInfoRef = ref()
const courseDirectoryRef = ref()
// 基本信息数据
const initDrawerData = ref({ basicInfo: {}, directory: [] })//校验数据是否修改过
const basicInfoData = ref()
const basicDraft = ref()
const directoryDraft = ref()
const directory = ref()
const isBasicDraft = computed(() => basicDraft.value && Object.keys(basicDraft.value).length > 0)
const isDirectoryDraft = computed(() => directoryDraft.value?.length > 0)
// 控制抽屉显示状态
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit('update:modelValue', value)
})
const isBasicInfo = computed(() => activeTab.value === BASIC_INFO)
const isAdd = computed(() => props.mode === 'add')
// 控制课程目录标签页是否禁用
const isCourseDirectoryDisabled = computed(() => {
  // 新增模式下，如果没有课程ID则禁用
  if (isAdd.value) {
    return !basicInfoData.value?.id
  }
  // 编辑模式下，如果没有props数据中的ID则禁用
  return !props.data?.id
})
const isEditDraft = computed(() => {
  return props.mode === 'edit' && props.data?.status === 'listed'
})
// 标题文本
const title = computed(() => {
  return isAdd.value ? $t('course.addCourse') : $t('course.editCourse')
})

const getCourseDirectory = async () => {
  // 如果没有课程ID，返回空数组
  if (!props.data?.id) {
    return []
  }
  return await getCourseDirectoryApi(props.data?.id as number)
}
const getCourseDetail = async () => {
  try {
    // 新增模式下，如果没有课程ID，直接初始化空数据
    if (!props.data?.id) {
      directory.value = []
      courseDirectoryRef.value?.setTreeData([])
      return
    }
    if (props.data?.hadDraft === HAD_DRAFT_MAP.YES) {
      const draftMap = await getCourseDetailApi(props.data?.id as number)
      // 添加空值检查
      if (!draftMap) return
      basicDraft.value = typeof draftMap.draft === 'string' ? JSON.parse(draftMap.draft) : draftMap.draft
      directoryDraft.value = typeof draftMap.directoryDraft === 'string' ? JSON.parse(draftMap.directoryDraft) : draftMap.directoryDraft
      if (basicDraft.value) {
        const { id, ...other } = { ...basicDraft.value }
        emit('update:data', { ...props.data, ...other })
      }
    }

    if (!directoryDraft.value?.length || directoryDraft.value?.length === 0) {
      directory.value = await getCourseDirectory()
    } else {
      directory.value = directoryDraft.value
    }

    // 添加数组检查，确保directory.value是数组
    if (!Array.isArray(directory.value)) {
      directory.value = []
    }

    directory.value = directory.value.map((item: any) => {
      let content = item.content ?? item.chapterContent
      // 如果content是字符串，尝试解析为JSON
      if (typeof content === 'string') {
        try {
          content = JSON.parse(content)
        } catch (e) {
          content = []
        }
      }
      // 确保content是数组
      if (!Array.isArray(content)) {
        content = []
      }

      return {
        ...item,
        type: NODE_TYPE.CHAPTER,
        content: content
      }
    })
    console.log('directory.value', directory.value)
    courseDirectoryRef.value?.setTreeData(directory.value)
    setInitDirectory(cloneDeep(directory.value))
  } catch (error) {
    // 出错时设置空数组，避免后续操作出错
    directory.value = []
    courseDirectoryRef.value?.setTreeData([])
    // ElMessage.error('获取课程详情失败')
  }
}
const setInitBasicInfo = (data: any) => {
  initDrawerData.value.basicInfo = data
}
const setInitDirectory = (data: any) => {
  initDrawerData.value.directory = data
}
// 监听props.data变化
watch(() => props.data, (newData) => {
  // 编辑模式下，如果有数据ID则使用数据
  if (newData?.id) {
    safeMergeObject(basicInfoData.value, newData)
  } else {
    basicInfoData.value = cloneDeep(initBasicInfoFormData)
  }
  setInitBasicInfo(cloneDeep(basicInfoData.value))
}, { immediate: true, deep: true })
// 监听抽屉打开状态，初始化basicInfoData
watch(() => visible.value, (newVal) => {
  basicInfoData.value = cloneDeep(initBasicInfoFormData)
  setInitBasicInfo(cloneDeep(basicInfoData.value))
  if (newVal) {
    getCourseDetail()
  }
})

// 处理关闭
const handleClose = () => {
  basicInfoRef.value?.resetForm()
  courseDirectoryRef.value?.resetForm()
  activeTab.value = BASIC_INFO
  courseDirectoryRef.value?.setTreeData([])
  courseDirectoryRef.value?.setDeleteChapterIds([])
  basicInfoData.value = { id: undefined }
  directoryDraft.value = null
  basicDraft.value = null
  initDrawerData.value.basicInfo = {}
  initDrawerData.value.directory = []
  emit('update:modelValue', false)
}

// 处理取消/返回
const handleCancel = () => {
  handleBeforeClose(() => {
    emit('cancel')
    handleClose()
  })
}

// 处理保存草稿
const handleSaveDraft = () => {
  handleConfirm(true)
}

// 处理基本信息更新
const handleBasicInfoUpdate = (data: any) => {
  basicInfoData.value = data
}

// 处理确定
const handleConfirm = async (draft: boolean = false) => {
  if (draft) {
    isSaveDraftLoading.value = true
    isLoading.value = false
  } else {
    isLoading.value = true
    isSaveDraftLoading.value = false
  }
  try {
    if (isBasicInfo.value) {
      await basicInfoRef.value?.validate()
      let api = draft ? saveDraftCourseInfoApi : isAdd.value ? createCourseInfoApi : updateCourseInfoApi
      setInitBasicInfo(cloneDeep(basicInfoData.value))
      const res = await api({ ...basicInfoData.value } as any)
      if (isAdd.value && res) {
        ElMessageBox.confirm($t('courseMgr.addSuccessGoManage'), '', {
          icon: SvgSuccessIcon,
          confirmButtonText: $t('common.submitTxt'),
          cancelButtonText: $t('common.cancelTxt'),
          dangerouslyUseHTMLString: true,
          type: 'success'
        }).then(() => {
          // 更新基本信息数据，设置课程ID
          basicInfoData.value.id = res
          // 通知父组件数据更新
          emit('update:data', { ...basicInfoData.value, id: res })
          // 切换到课程目录标签页
          activeTab.value = COURSE_DIRECTORY
          // 重置课程目录表单
          courseDirectoryRef.value?.resetForm()
          // 显示成功提示
          ElMessage.success($t('course.createSuccess'))
        }).catch(() => {
          // 用户选择返回，不做任何操作
          console.log('用户选择返回')
        })
      } else {
      }
    } else if (activeTab.value === COURSE_DIRECTORY) {
      await courseDirectoryRef.value?.validate()
      const courseData = await courseDirectoryRef.value?.getTreeData()
      setInitDirectory(cloneDeep(courseData))
      const submitData = {
        courseId: props.data?.id,
        deleteChapterIds: courseDirectoryRef.value?.getDeleteChapterIds(),
        chapters: courseData.map((item: any) => ({
          ...item,
          content: JSON.stringify(item.content)
        }))
      }
      console.log('submitData', submitData, courseData)
      const api = draft ? saveDraftCourseDirectoryApi : createCourseDirectoryApi
      await api(submitData)
    }
    emit('confirm', basicInfoData.value as CourseItem)
    if (!isAdd.value || (isAdd.value && !isBasicInfo.value)) {
      handleClose()
    }
  } catch (error) {
  } finally {
    isLoading.value = false
    isSaveDraftLoading.value = false
  }
}

const isCheckBasicInfoChange = () => {
  return isEqual(initDrawerData.value.basicInfo, basicInfoData.value)
}

const isCheckDirectoryChange = (courseData: any) => {
  return isEqual(initDrawerData.value.directory, courseData)
}

const checkDataChange = async () => {
  const courseData = await courseDirectoryRef.value?.getTreeData()
  if (isCheckBasicInfoChange() && isCheckDirectoryChange(courseData)) {
    return true
  }
  return false
}
const boxText = async (): Promise<boolean> => {
  try {
    // await ElMessageBox.confirm($t('courseMgr.leaveConfirm'), {
    //   icon: SvgFailIcon,
    //   confirmButtonText: $t('common.submitTxt'),
    //   cancelButtonText: $t('common.cancelTxt'),
    //   dangerouslyUseHTMLString: true,
    // })
    await confirm($t('courseMgr.leaveConfirm'), {})
    return true
  } catch {
    return false
  }
}

const handleBeforeClose = async (done: () => void) => {
  if (!isAdd.value) {
    const isCheck = await checkDataChange()
    if (!isCheck) {
      const res = await boxText()
      if (!res) return
    }
  }
  done()
}

</script>

<style scoped>
.drawer-content {
  min-height: 400px;
  /* padding: 20px 0; */
}

.course-tabs {
  height: 100%;
}

.course-tabs :deep(.el-tabs__content) {
  height: calc(100% - 55px);
  overflow-y: auto;
}

.edit-btn-wrapper {
  position: relative;
  display: inline-block;
}

.draft-dot {
  position: absolute;
  top: -4px;
  right: -5px;
  width: 8px;
  height: 8px;
  background: #ff3b30;
  border-radius: 50%;
  z-index: 1;
}

.disabled-tab {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
